var fs = require('fs'), system = require('system');
var index = 0, str_Url = [], unable_str ='', openURL, RenderUrlsToFile;
if(system.args.length < 2) {
	console.log("the phantomjs usage is --> phantomjs XX.js theURLstring");
	phantom.exit();
}else {
	openURL = system.args[1];
	var str_Url = openURL.split(',');
}
if(str_Url.length > 100) {
	console.log("phantomjs run once only open 100 page");
	phantom.exit();
}
//Render Multiple URLs to file

RenderUrlsToFile = function(urls, callbackPerUrl, callbackFinal) {
	var next, page, retrieve, webpage;
	webpage = require("webpage");
	page = null;
	next = function(status, url) {
		page.close();
		callbackPerUrl(status, url);
		return retrieve();
	};
	retrieve = function() {
		var url, startTime;
		if (urls.length > 0) {
			url = urls.shift();
			page = webpage.create();
			page.viewportSize = {
				width: 1280,
				height: 800
			};
			page.settings.resourceTimeout = 4000;
			page.settings.loadImages = false;
			page.settings.userAgent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36';
			page.onResourceTimeout = function(e) {
				unable_str = "can not open the page the url is: " + url + "\r\n";
				fs.write('unable.txt', unable_str, 'a');
				url = urls.shift();
			};
			return page.open(url, function(status) {
				var t, time;
				if (status == "success") {
					startTime = new Date().getTime();
					var goodsId = url.split('com/')[1].split('.')[0];
					console.log('open success');
					var goods_data = {
						"img_link": null
					};
					//打开后发现商品已经下架
					var errorFlag = false;
					//var errorFlag = page.evaluate(function() {
					//	var errorName = document.getElementsByClassName('error-notice-hd')[0];
					//	if(errorName == undefined) {
					//		return false;
					//	}else {
					//		return true;
					//	}
					//});
					if(errorFlag == true) {
						unable_str = "Goods from the shelves url is: " + url + "\r\n";
						fs.write('unable.txt', unable_str, 'a');
						return next(status, url);
					}else {

						return function() {
							//图片的URL

							function checkReadyState() {

								var timer = setInterval(function () {

									var readyState = page.evaluate(function () {
										return document.readyState;
									});
									console.log('readyState:' + readyState);
									if ("complete" === readyState) {
										console.log('not shelves complete');
										var link_array = page.evaluate(function() {
											//判断是否包含某个class名
											function hasClass(className,node){
												var classNames = node.className.split(/\s+/);
												for(var i = 0; i < classNames.length; i++){
													if(classNames[i] == className){
														return true;
													}
												}
												return false;
											}
											var wrap = document.getElementById("J-detail-content");
											var img = document.querySelectorAll("#J-detail-content img");
											var img_array = [], index = 0;
											if(typeof img != 'undefined' && img.length >= 1){
												var img_list =  document.querySelectorAll("#J-detail-content img");
												for(var m = 0; m < img_list.length; m++) {
													var img_url;
													if(img_list[m].getAttribute('data-lazyload') == null) {
														img_url = img_list[m].src;
													}else {
														img_url = img_list[m].getAttribute('data-lazyload');
													}
													//if(hasClass('desc_anchor', img_list[m]) == true){
                                                    //
													//}else {
														img_array[index++] = img_url;
													//}
												}
												img_array[img_array.length] = true;
											}
											return img_array;
										});
										//数组去重和删除start图片
										function removeDuplicatedItem(ar) {
											var ret = [];
											for(var i = 0; i <ar.length; i++) {
												if (ret.indexOf(ar[i]) === -1 && ! (/\?{1}/gi.test(ar[i]))) {
													ret.push(ar[i]);
												}
											}
											return ret;
										}
										if(link_array[link_array.length-1] == true){
											clearInterval(timer);
											link_array.length = link_array.length - 1;
											var img_linkArray = removeDuplicatedItem(link_array);
											goods_data.img_link = img_linkArray;
										}
									} else {
										checkReadyState();
									}
								}, 500);
							}
							checkReadyState();

							var data_timer = window.setInterval(function() {
								var nowDate = new Date().getTime();
								if(nowDate > (parseInt(startTime) + 5 * 1000)) {
									clearInterval(data_timer);
									console.log("the page load more than 10s:"+ url);
									unable_str = "the page load is more than 10 seconds url is: " + url + "\r\n";
									fs.write('unable.txt', unable_str, 'a');
									return next(status, url);
								}
								if(goods_data["img_link"] != null ) {
									clearInterval(data_timer);
									var last = JSON.stringify(goods_data);
									var path = "jingdongtxt/"  + goodsId + ".txt";
									if(fs.exists(path)) {
										console.log("the txtFile is exists");
									}else {
										try{
											fs.write("jingdongtxt/"+ goodsId + ".txt", last, 'a');
										}catch(e){
											console.log(e);
										}
									}
									console.log("present url output data success");
									return next(status, url);
								}
							}, 200);
						}();
					}
				} else {
					return next(status, url);
				}
			});
		} else {
			return callbackFinal();
		}
	};
	return retrieve();
};

RenderUrlsToFile(str_Url, (function(status, url) {
	if (status !== "success") {
		unable_str = "the page is open faild url is: " + url + "\r\n";
		fs.write('unable.txt', unable_str, 'a');
		return console.log("fail open the page:" + url);
	}
}), function() {
	return phantom.exit();
});
